use std::{fs, path::PathBuf, str::FromStr};

use crate::{chunk::Chunk, chunk_type::ChunkType, png::Png};

pub struct Commands {}
impl Commands {
    pub fn get_png(file_path: PathBuf) -> Result<Png, &'static str> {
        if let Ok(png_data) = fs::read(file_path) {
            Png::try_from(png_data.as_slice())
        } else {
            Err("文件打开失败，可能是文件不存在")
        }
    }

    pub fn print(file_path: PathBuf) {
        if let Ok(png) = Self::get_png(file_path) {
            for (i, chunk) in png.chunks().iter().enumerate() {
                println!(
                    "{}: length: {}, chunk_type: {}",
                    i + 1,
                    chunk.length,
                    chunk.chunk_type.to_string()
                );
            }
        } else {
            println!("文件不存在或者不是一个有效的PNG格式文件！");
        }
    }
    pub fn encode(file_path: PathBuf, chunk_type: String, message: String) {
        if let Ok(mut png) = Self::get_png(file_path.clone()) {
            let chunk_result = ChunkType::from_str(&chunk_type);
            if chunk_result.is_err() {
                println!("chunk_type格式不正确");
                return;
            }
            let new_chunk_type = chunk_result.unwrap();
            let data: Vec<u8> = message.as_bytes().try_into().unwrap();
            let new_chunk = Chunk::new(new_chunk_type, data);
            png.insert_before_end(new_chunk);
            if let Err(e) = fs::write(file_path.clone(), png.as_bytes()) {
                print!("{e}")
            }
        } else {
            println!("文件不存在或者不是一个有效的PNG格式文件！");
        }
    }
    pub fn decode(file_path: PathBuf, chunk_type: String) {
        if let Ok(png) = Self::get_png(file_path.clone()) {
            let chunk_result = ChunkType::from_str(&chunk_type);
            if chunk_result.is_err() {
                println!("chunk_type格式不正确");
                return;
            }
            let new_chunk_type = chunk_result.unwrap();
            for c in png.chunks() {
                if c.chunk_type == new_chunk_type {
                    println!("Chunk: {}", c.to_string())
                }
            }
        } else {
            println!("文件不存在或者不是一个有效的PNG格式文件！");
        }
    }

    pub fn remove(file_path: PathBuf, chunk_type: String) {
        if let Ok(mut png) = Self::get_png(file_path.clone()) {
            let res = png.remove_first_chunk(chunk_type.as_str());
            if res.is_ok() {
                println!("移除成功");
            } else {
                println!("移除失败")
            }
        } else {
            println!("文件不存在或者不是一个有效的PNG格式文件！");
        }
    }
}
